import { Router, Request, Response, NextFunction } from "express";
import { uploadImages } from "../controllers/uploadController";
import multer from "multer";

// 配置 multer 存储
const storage = multer.memoryStorage();
const upload = multer({ 
  storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // 限制文件大小为 5MB
  },
  fileFilter: (req, file, cb) => {
    // 只允许上传图片文件
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传图片文件！'));
    }
  }
});

const router = Router();

// 错误处理中间件
const handleMulterError = (err: any, req: Request, res: Response, next: NextFunction) => {
  if (err instanceof multer.MulterError) {
    // Multer 错误处理
    console.error('Multer 错误:', err);
    if (err.code === 'LIMIT_FILE_SIZE') {
      return res.status(400).json({ error: '文件大小超过限制（最大 5MB）' });
    }
    return res.status(400).json({ error: `文件上传错误: ${err.message}` });
  } else if (err) {
    // 其他错误
    console.error('文件上传错误:', err);
    return res.status(500).json({ error: err.message });
  }
  next();
};

// 上传路由
router.post("/upload", 
  (req: Request, res: Response, next: NextFunction) => {
    console.log('接收到上传请求');
    next();
  },
  upload.array("images", 10),
  handleMulterError,
  uploadImages
);

export default router;